<?php

/**
 *
 * @author lovebing <lovebing365@126.com> Created on 2015-2-13
 */
class LogUtil {

    public static function exception(Exception $ex) {
        $file = self::getFilePath('exception');
        if ($file === false) {
            return;
        }
        $code = $ex->getCode();
        $msg = $ex->getMessage();
        $efile = $ex->getFile();
        $eline = $ex->getLine();
        $critical = is_a($ex, 'RuntimeException') ? '0' : '1';

        $data = date('Y-m-d H:i:s') . "|{$msg}|{$code}|{$eline}|{$efile}|{$critical}\n";
        @file_put_contents($file, $data, FILE_APPEND);
    }

    /**
     * 
     * @param type $data
     * @return type
     */
    public static function info($data) {
        $file = self::getFilePath('info');
        if ($file === false) {
            return;
        }
        if(is_object($data) || is_array($data)) {
            $data = json_encode($data);
        }
        $data = date('Y-m-d H:i:s') . "|{$data}\n";
        @file_put_contents($file, $data, FILE_APPEND);
    }

    public static function error(CErrorEvent $error) {
        $file = self::getFilePath('error');
        if ($file === false) {
            return;
        }
        $data = date('Y-m-d H:i:s') . "|{$error->message}|{$error->code}|{$error->line}|{$error->file}\n";
        @file_put_contents($file, $data, FILE_APPEND);
    }

    private static function getFilePath($logType) {
        if (!isset(Yii::app()->params['logPath']) || !is_dir(Yii::app()->params['logPath'])) {
            return false;
        }
        $logPath = Yii::app()->params['logPath'];
        $dir = $logPath . '/' . $logType;
        if (!is_dir($dir)) {
            @mkdir($dir);
        }
        $file = $dir . '/' . date('Ymd') . '.txt';
        return $file;
    }

}
